package com.ripplezjw.blog.controller;

import com.ripplezjw.blog.Service.UserService;
import com.ripplezjw.blog.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/loginTo")
    public String loginTo(User user, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        User userFromDB = userService.loginUser(user.getUsername(), user.getPassword());
        System.out.println(userFromDB);
        if (userFromDB != null) {
            // 登陆成功
            request.getSession().setAttribute("user_info", userFromDB);
            return "redirect:/index";
        } else {
            // 登陆失败
            redirectAttributes.addFlashAttribute("login_error_msg", "用户名或密码错误，请重新输入");
            return "redirect:/login";
        }
    }
}
